package kpython.backend.stackframe;

import java.io.BufferedWriter;
import java.io.IOException;

public class PrintableStackFrame {
    
    
	public static void initStack(BufferedWriter writer) {
		try {		
			writer.append("//---- INICIA STACK --------\n");						
			writer.append("frame *sp = NULL;\n");
			writer.append("frame *master = NULL;\n");	
			writer.append("stackN *fs = (stackN *)malloc(sizeof(stackN));\n");
			writer.append("fs->bellow = NULL;\n");
			writer.append("fs->content = NULL;\n");
			writer.append("stackN *tmp = NULL;\n");
			writer.append("sp = (frame*)malloc(sizeof(frame));\n");			
			writer.append("sp->return_address = 0;\n");
			writer.append("sp->locals = NULL;\n");
			writer.append("fs->content = sp;\n");
			writer.append("master = sp;\n");
			writer.append("//---- END --------\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public static void initLocals(BufferedWriter writer, int nlocals) {
		try {
			if(nlocals>0)
				writer.append("//-----INICIA LOCALS-------\n");
				writer.append("sp->locals = (var*)malloc("+nlocals+"*sizeof(var));\n");
				writer.append("//---- END --------\n");
		}catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public static void pushFrame(BufferedWriter writer, int ra) {
		try {	
			writer.append("//----- PUSH ------\n");
			writer.append("tmp = fs;\n");			
			writer.append("fs = (stackN *)malloc(sizeof(stackN));\n");
			writer.append("fs->bellow = tmp;\n");
			writer.append("sp = (frame *)malloc(sizeof(frame));\n");						
			writer.append("sp->return_address = "+ra+";\n");
			writer.append("sp->locals = NULL;\n");
			writer.append("fs->content = sp;\n");
			writer.append("//----- END ------\n");
		}catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	public static void popFrame(BufferedWriter writer) {
		try {	
			writer.append("//------- POP ----------\n");			
			writer.append("tmp = fs;\n");
			writer.append("fs = tmp->bellow;\n");
			writer.append("free(tmp->content);\n");			
			writer.append("free(tmp);\n");
			writer.append("sp = fs->content;\n");    
			writer.append("_ra = sp->return_address;\n");
			writer.append("//------- END ----------\n");		
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}
